package com.project.forlearning.controller;

import com.alibaba.fastjson.JSON;
import com.project.forlearning.pojo.vo.ResponseInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

/**
 * 文件上传
 */
@Api(value = "FileController",tags = {"文件上传"})
@RestController
@RequestMapping("file")
@CrossOrigin
public class FileController {

     @Value("${file.upload.picPath}")
     private String picPath;

     /**
      * 图片上传
      */
     @ApiOperation("图片上传")
     @RequestMapping("pic")
     public String upload(@ApiParam(value = "文件",required = true) @RequestParam("file") MultipartFile file) throws IOException {

          String filename = file.getOriginalFilename();
          if(filename == null) throw new NullPointerException();
          String type = filename.substring(filename.lastIndexOf("."));
          String newFileName = UUID.randomUUID() + type;
          String fPath = picPath + File.separator + newFileName;
          //文件上传
          file.transferTo(new File(fPath));
          return JSON.toJSONString(new ResponseInfo<>(200, "文件上传成功", newFileName));
     }
}
